package www.truongnha.com;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import Config.setting;
import TruongNhaLib.JSONParser;
import TruongNhaLib.Lesson;
import TruongNhaLib.Schedule;
import TruongNhaLib.UserFunctions;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class TimeTable extends Activity{
    private Schedule  schedule = new Schedule();
    GridView grid;
    ListAdapter MonAdapter ;
    ArrayList<HashMap<String, String>> time = new ArrayList<HashMap<String,String>>();
	//private ArrayAdapter<Lesson> adapter;
    private Intent doneLoading;
    private static String host = setting.getHost();
    private static String url_schedule = host + "api/schedule/";
	
	@SuppressWarnings("deprecation")
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.timetable);
	    schedule = (Schedule) getLastNonConfigurationInstance();
		if (schedule == null) {
			//get time task in thread
			Log.d("schedule == ", "null");
			new getTimeTask().execute(url_schedule);			 	
		} else{
		    List<Lesson> MonList = schedule.getMon();
		    for(int i = 0 ; i< MonList.size(); i++ ){
		    	HashMap<String,String> lesson = new HashMap<String,String>();
			    lesson.put("time", MonList.get(i).getTime()+"");
			    lesson.put("className", MonList.get(i).getClsName());
			    lesson.put("subject", MonList.get(i).getSub());
			    time.add(lesson);
		    }
		 }
	    // Get data for main Class
  		MonAdapter = new SimpleAdapter(TimeTable.this, time,
	                R.layout.lesson_item,
	                new String[] { "time", "className", "subject"}, new int[] {
	                        R.id.time ,R.id.className, R.id.subject});
  		Log.d("time", "3");
  		//Set adapter  
		grid = (GridView)findViewById(R.id.grid2);
		grid.setAdapter(MonAdapter);

	 }


	@Override
	public Object onRetainNonConfigurationInstance() {
		// TODO Auto-generated method stub
		Log.d("retain schedule", " ");
		return schedule;
	}

	/**
	 * Press back button twice to exit
	 */
	private long lastPressedTime;
	private Toast toast;
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
	        switch (event.getAction()) {
	        case KeyEvent.ACTION_DOWN:
	            if (event.getDownTime() - lastPressedTime < setting.PERIOD_TWICE_TO_EXIT) {
	            	toast.cancel();
	                finish();
	            } else {
	            	toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
	            	toast.setText("Nhấn back một lần nữa để thoát | time table");
	            	toast.show();
	                lastPressedTime = event.getEventTime();
	            }
	            return true;
	        }
	    }
	    return false;
	}

	class getTimeTask extends AsyncTask<String, Void, Void>{
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			doneLoading = new Intent();
            doneLoading.setAction("DONE_LOADING_ACTION");
            doneLoading.putExtra("doneLoading", false);
            getApplicationContext().sendBroadcast(doneLoading);
			Log.d("Time", "start Load");
		}
		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub
	        JSONObject timeObject = new JSONParser().getJSONObject(params[0]);
			schedule = new Schedule(timeObject , UserFunctions.userType( getApplicationContext() ));
	        return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			//Broadcast to main activity when done loading
			doneLoading = new Intent();
            doneLoading.setAction("DONE_LOADING_ACTION");
            doneLoading.putExtra("doneLoading", true);
            getApplicationContext().sendBroadcast(doneLoading);            

		    List<Lesson> MonList = schedule.getMon();
		    for(int i = 0 ; i< MonList.size(); i++ ){
		    	HashMap<String,String> lesson = new HashMap<String,String>();
			    lesson.put("time", MonList.get(i).getTime()+"");
			    lesson.put("className", MonList.get(i).getClsName());
			    lesson.put("subject", MonList.get(i).getSub());
			    //Log.d("add", "object " +i);
			    time.add(lesson);
		    }
		    ((BaseAdapter) MonAdapter).notifyDataSetChanged();
			Log.d("Time", "Done");
		}
	}//End class getTimeTask

}
